package com.example.spring_blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.spring_blog.common.constant.Constants;
import com.example.spring_blog.common.exception.BlogException;
import com.example.spring_blog.common.util.BeanTransUtils;
import com.example.spring_blog.common.util.JwtUtils;
import com.example.spring_blog.common.util.SecurityUtils;
import com.example.spring_blog.mapper.BlogInfoMapper;
import com.example.spring_blog.mapper.UserInfoMapper;
import com.example.spring_blog.pojo.dataobject.BlogInfo;
import com.example.spring_blog.pojo.dataobject.UserInfo;
import com.example.spring_blog.pojo.request.UpdateAvatarRequest;
import com.example.spring_blog.pojo.request.UpdateUserRequest;
import com.example.spring_blog.pojo.request.UserLoginRequest;
import com.example.spring_blog.pojo.request.UserRegisterRequest;
import com.example.spring_blog.pojo.response.Result;
import com.example.spring_blog.pojo.response.UserInfoResponse;
import com.example.spring_blog.pojo.response.UserLoginResponse;
import com.example.spring_blog.service.BlogService;
import com.example.spring_blog.service.UserService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private BlogInfoMapper blogInfoMapper;

    // 头像的存储路径
    @Value("${avatar.save-path}")  // 在application.yml中配置
    private String savePath;

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;

    @Override
    public UserLoginResponse checkPassword(UserLoginRequest userLoginRequest) {
        // 查询数据库
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        // 用户名相同，并且deleteFlag == 0
        queryWrapper.lambda()
                .eq(UserInfo::getUserName, userLoginRequest.getUserName())
                .eq(UserInfo::getDeleteFlag, 0);

        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
        if (userInfo == null) {
            throw new BlogException("用户不存在");
        }

        // 判断密码是否相同
//        if (!userInfo.getPassword().equals(userLoginRequest.getPassword())) {
//            throw new BlogException("密码错误");
//        }

        // 判断加密后的密码是否相同
        if (!SecurityUtils.check(userLoginRequest.getPassword(), userInfo.getPassword())) {
            throw new BlogException("密码错误");
        }

        // 密码正确
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userInfo.getId());
        map.put("userName", userInfo.getUserName());
        // 生成token
        String token = JwtUtils.genJwt(map);

        return new UserLoginResponse(userInfo.getId(), token);
    }

    @Override
    @SneakyThrows
    public Boolean registerUserInfo(UserRegisterRequest userRegisterRequest) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userRegisterRequest, userInfo);

        // 对密码进行加密
        String encrypt = SecurityUtils.encrypt(userInfo.getPassword());
        userInfo.setPassword(encrypt);
        try {
            userInfoMapper.insert(userInfo);
        } catch (RuntimeException e) {
            throw new BlogException("该用户已经存在，请更换用户名！");
        }
        // 上传头像
        // 构造上传头像的请求类
        UpdateAvatarRequest updateAvatarRequest = new UpdateAvatarRequest();
        updateAvatarRequest.setId(userInfo.getId());
        updateAvatarRequest.setAvatarPath(userRegisterRequest.getAvatarPath());
        UserInfoResponse userInfoResponse = uploadAvatar(updateAvatarRequest);
        return userInfoResponse != null;
    }

    /**
     * 根据用户id获取用户信息
     * @param userId
     * @return
     */
    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        // 查询用户信息
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserInfo::getId, userId)
                .eq(UserInfo::getDeleteFlag, 0);
        UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

        // 查询这个用户发布的文章数量
        QueryWrapper<BlogInfo> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.lambda().eq(BlogInfo::getUserId, userId)
                        .eq(BlogInfo::getDeleteFlag, Constants.BLOG_NORMAL_NUM);
        List<BlogInfo> blogInfos = blogInfoMapper.selectList(queryWrapper1);
        if (userInfo == null || userInfo.getId() < 0) {
            throw new BlogException("没有查到这个用户的信息");
        }
        return BeanTransUtils.trans(userInfo, blogInfos.size());
    }

    /**
     * 根据博客id获取作者信息
     * @param blogId
     * @return
     */
    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        // 先根据博客id获取这个博客的信息
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if (blogInfo == null || blogInfo.getUserId() < 0) {
            throw new BlogException("没有查到博客信息");
        }
        return getUserInfo(blogInfo.getUserId());
    }

    @Override
    public Boolean updateUserInfo(UpdateUserRequest updateUserRequest) {
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(updateUserRequest, userInfo);
        try {
            // 根据用户id找到用户的信息进行更新
            int i = userInfoMapper.updateById(userInfo);
            if (i > 0) {
                return true;
            }
        } catch (Exception e) {
            log.error("更新失败, e : "+ e);
            throw new BlogException("更新失败，请联系管理员！");
        }
        return false;
    }

    @SneakyThrows
    @Override
    public UserInfoResponse uploadAvatar(UpdateAvatarRequest updateAvatarRequest) {
        MultipartFile file = updateAvatarRequest.getAvatarPath();
        Integer userId = updateAvatarRequest.getId();


        // 1. 生成唯一文件名（用户ID_uuid.扩展名）
        String originalFilename = file.getOriginalFilename();
        String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
        if (!fileExt.equalsIgnoreCase(".jpg") && !fileExt.equalsIgnoreCase(".png")) {
            throw new BlogException("仅支持 JPG/PNG 格式！");
        }
        String newFilename = userId + "_" + UUID.randomUUID() + fileExt;

        // 2.创建保存目录
        Path uploadDir = Paths.get(savePath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);  // 自动创建多级目录
        }

        // 2. 保存文件到本地
        Path filePath = uploadDir.resolve(newFilename);
        Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

        // 3. 保存到数据库 存放头像的相对路径
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatarPath("/avatars/" + newFilename);
        try {
            int i = userInfoMapper.updateById(userInfo);
            if (i > 0) {
                return BeanTransUtils.trans(userInfo);
            }
        } catch (Exception e) {
            throw new BlogException("上传头像失败，请检查网络！");
        }
        return null;
    }
}
